package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.Result;
import io.renren.dao.AuxiliaryMateriDao;
import io.renren.dao.AuxiliaryMaterialsmxDao;
import io.renren.dto.*;
import io.renren.entity.AuxiliaryMateriEntity;
import io.renren.entity.UserEntity;
import io.renren.service.*;
import io.renren.utils.StringsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 辅材采购表
 *
 * @author 罗胜平 781757616@qq.com
 * @since 1.0.0 2019-11-22
 */
@Service
public class AuxiliaryMateriServiceImpl extends CrudServiceImpl<AuxiliaryMateriDao, AuxiliaryMateriEntity, AuxiliaryMateriDTO> implements AuxiliaryMateriService {
    @Autowired
    private AuxiliaryMateriService auxiliaryMateriService;
    @Autowired
    private AuxiliaryMaterialsmxService auxiliaryMaterialsmxService;
    @Autowired
    private AuxiliaryMateriDao auxiliaryMateriDao;
    @Autowired
    private AuxiliaryMaterialsmxDao auxiliaryMaterialsmxDao ;
    @Autowired
    private FoodmxService foodmxService;
    @Autowired
    private FinanceService financeService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private TemporaryOrderService temporaryOrderService;
    @Autowired
    private TemporaryOrdermxService temporaryOrdermxService;
    @Override
    public QueryWrapper<AuxiliaryMateriEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<AuxiliaryMateriEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.orderByDesc("create_date");
        return wrapper;
    }


    @Override
    public List<AuxiliaryMateriDTO> selectHome(Map<String, Object> params) {
        QueryWrapper<AuxiliaryMateriEntity> wrapper =new QueryWrapper<>();
        wrapper.orderByDesc("create_date").last("limit 10");
        List<AuxiliaryMateriEntity> auxiliaryMateriEntities = baseDao.selectList(wrapper);
        return ConvertUtils.sourceToTarget(auxiliaryMateriEntities, AuxiliaryMateriDTO.class);
    }

    @Transactional
    public void saveAuxiliaryOrder(JSONObject params, UserEntity entity) {
        System.out.println(params);
        String materialsId1 = (String) params.get("auxiliaryMaterialsId");
        if(StringUtils.isNotBlank(materialsId1)){
            auxiliaryMateriService.deleteById(Long.parseLong(materialsId1));
            auxiliaryMaterialsmxService.deleteOrder(Long.parseLong(materialsId1));

        }
        AuxiliaryMateriDTO auxiliaryMateriDTO = new AuxiliaryMateriDTO();
        String chedId = (String) params.get("chedId");
        auxiliaryMateriDTO.setChedId(Long.parseLong(chedId));
        auxiliaryMateriDTO.setCreateDate(new Date());
        auxiliaryMateriDTO.setCanteenId(entity.getDeptId());
        auxiliaryMateriService.save(auxiliaryMateriDTO);//保存
        Long auxiliaryMaterialsId = auxiliaryMateriDTO.getAuxiliaryMaterialsId();
        ArrayList<LinkedHashMap> list = (ArrayList) params.get("list");
        for(int i=0 ;i<list.size() ;i++){
            LinkedHashMap<String,Object> list1 =list.get(i);
            String supplierId = (String)list1.get("supplierId");
            if(null!=supplierId){
                ArrayList<LinkedHashMap> foods = (ArrayList)list1.get("foods");
                for(int j=0 ;j<foods.size() ;j++){
                    AuxiliaryMaterialsmxDTO auxiliarymxDTO = new AuxiliaryMaterialsmxDTO();
                    String foodId = (String)foods.get(j).get("foodId");
                    auxiliarymxDTO.setFoodId(Long.parseLong(foodId));
                    auxiliarymxDTO.setSupplierId( Long.parseLong(supplierId));
                    Float num =1F;
                   // Integer purchaseNum =(Integer)foods.get(j).get("purchaseNum");
                    String purchaseNum =String.valueOf(foods.get(j).get("purchaseNum"));
                    if(null !=purchaseNum){
                        num =Float.parseFloat(purchaseNum);
                    }
                    auxiliarymxDTO.setPurchaseNum(num);

                    auxiliarymxDTO.setAuxiliaryMaterialsId(auxiliaryMaterialsId);
                    auxiliaryMaterialsmxService.save(auxiliarymxDTO);
                }
            }
        }
        TemporaryOrderDTO temOrder = temporaryOrderService.getTemOrder(1, entity.getId(), entity.getDeptId());
        temporaryOrderService.deleteOrder(1,entity.getDeptId());
        temporaryOrdermxService.deleteOrder(temOrder.getTemporaryId());
    }

    @Override
    public PageData<AuxiliaryMateriDTO> pageAdmin(Map<String, Object> params) {
        String canteenid = (String)params.get("canteenId");
        QueryWrapper<AuxiliaryMateriEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status",1);
        wrapper.orderByDesc("create_date");
        wrapper.eq(StringUtils.isNotBlank(canteenid),"canteen_id", Long.parseLong(canteenid));
        IPage<AuxiliaryMateriEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, AuxiliaryMateriDTO.class);
    }

    @Override
    public PageData<AuxiliaryMateriDTO> pageChef(Map<String, Object> params) {
        QueryWrapper<AuxiliaryMateriEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status",5);
        wrapper.orderByDesc("create_date");
        IPage<AuxiliaryMateriEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, AuxiliaryMateriDTO.class);
    }

    @Override
    public PageData<AuxiliaryMateriDTO> pagesTorehouseClerk(Map<String, Object> params, UserEntity entity) {
        QueryWrapper<AuxiliaryMateriEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status", 3).orderByDesc("create_date");
        wrapper.eq("canteen_id",entity.getDeptId());
        IPage<AuxiliaryMateriEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, AuxiliaryMateriDTO.class);
    }

    @Override
    public PageData<AuxiliaryMateriDTO> getOrder(Map<String, Object> params, UserEntity entity) {
        QueryWrapper<AuxiliaryMateriEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("canteen_id",entity.getDeptId()).orderByDesc("create_date");
        IPage<AuxiliaryMateriEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        PageData<AuxiliaryMateriDTO> pageData = getPageData(page, AuxiliaryMateriDTO.class);
        return pageData ;
    }

    @Override
    public Result updateExamine(AuxiliaryMateriDTO dto, UserEntity userEntity) {
        //如果到货数量或者照片没有传抛出异常
        if(3==dto.getStatus()){
            //根据订单号查询详情 并遍历，判断空
            List<AuxiliaryMaterialsmxDTO> stockOrdermxDTOList = auxiliaryMaterialsmxService.selectGyss(dto.getAuxiliaryMaterialsId());
            for (AuxiliaryMaterialsmxDTO materialsmxDTO:stockOrdermxDTOList) {
                if(1 ==materialsmxDTO.getSubStatus()){
                    List<AuxiliaryMaterialsmxDTO> materialsmxDTOList = auxiliaryMaterialsmxService.selectFoods(materialsmxDTO.getAuxiliaryMaterialsId(), materialsmxDTO.getSupplierId());
                    for (AuxiliaryMaterialsmxDTO auxiliaryMaterialsmxDTO:materialsmxDTOList) {
                        if(0!=auxiliaryMaterialsmxDTO.getArrivalNum()) {
                            if (null == auxiliaryMaterialsmxDTO.getArrivalNum() || StringUtils.isBlank(auxiliaryMaterialsmxDTO.getEntityPhoto())) {
                                Result result = new Result();
                                return result;
                            }
                        }
                    }
                }
            }
        }

        if (dto.getStatus()==3){
            dto.setStatus(4);
            dto.setReceivingGoodsTime(new Date());
            dto.setStorehouseClerkId(userEntity.getId());
        }
        if (dto.getStatus()==1){
            dto.setStatus(2);
            dto.setAuditTime(new Date());
            dto.setCanteenAdminId(userEntity.getId());
        }
        update(dto);
        if(4==dto.getStatus()){
            //辅材的数据入库
            foodmxService.saveFoodmx(dto.getAuxiliaryMaterialsId(),userEntity.getDeptId());
            saveFinance(dto.getAuxiliaryMaterialsId(),userEntity.getDeptId());
        }
        return new Result();
    }

    @Override
    public Result UpdateSupplierOrder(AuxiliaryMateriDTO dto, UserEntity userEntity) {
        List<AuxiliaryMaterialsmxDTO> materialsmxDTOList = auxiliaryMaterialsmxService.seletGysFood1(dto.getAuxiliaryMaterialsId(), userEntity.getId());
        for (AuxiliaryMaterialsmxDTO materialsmxDTO:materialsmxDTOList) {
            auxiliaryMaterialsmxService.updateOrder1(materialsmxDTO.getAuxiliaryMaterialsmxId(),1);
        }

        AuxiliaryMateriDTO auxiliaryMateriDTO = auxiliaryMateriService.get(dto.getAuxiliaryMaterialsId());
        if(2==auxiliaryMateriDTO.getStatus()){
            dto.setStatus(3);
            dto.setOfferTime(new Date());
            dto.setSupplierId(userEntity.getId());
                update(dto);

        }
        return new Result();
    }

    /**
     * 生成财务订单
     * @param order
     */
    void saveFinance(Long order,Long  canteenid){
        List<AuxiliaryMaterialsmxDTO> materialsmxDTOList = auxiliaryMaterialsmxDao.gys1(order);
        for (AuxiliaryMaterialsmxDTO auxiliarymx:materialsmxDTOList) {
            Float total=0F;
            List<AuxiliaryMaterialsmxDTO> list = auxiliaryMaterialsmxService.selectFoods(auxiliarymx.getAuxiliaryMaterialsId(), auxiliarymx.getSupplierId());
            for (AuxiliaryMaterialsmxDTO materialsmx: list ) {
                Float mult = StringsUtils.mult(materialsmx.getArrivalNum(), materialsmx.getUnitPrice());
                total = total + mult;
            }
            FinanceDTO financeDTO = new FinanceDTO();
            financeDTO.setAmountPayable(total);
            financeDTO.setSupplierId(auxiliarymx.getSupplierId());
            financeDTO.setOrderid(auxiliarymx.getAuxiliaryMaterialsId());
            financeDTO.setFinanceId(auxiliarymx.getFinanceId());
            financeDTO.setSupplierId(auxiliarymx.getSupplierId());
            financeDTO.setCreateDate(auxiliarymx.getCreateDate());
            financeDTO.setCanteenId(canteenid+"");
            financeDTO.setType("2");
            financeService.save(financeDTO);
        }
    }
    /**
     * 辅材供应商列表
     * @param supplierId
     * @return
     */
    @Override
    public Map selecSupplierMateriOrder(Long supplierId) {
        List<AuxiliaryMateriDTO> auxiliaryList = auxiliaryMateriDao.selecSupplierMateriOrder(supplierId);
        ArrayList<AuxiliaryMateriDTO> auxiliaryDTO = new ArrayList<>();
        for (AuxiliaryMateriDTO materiDTO :auxiliaryList) {
            List<AuxiliaryMaterialsmxDTO> list = auxiliaryMaterialsmxService.seletGysFood1(materiDTO.getAuxiliaryMaterialsId(), supplierId);
            if(list.size()>0){
                AuxiliaryMaterialsmxDTO materialsmxDTO = list.get(0);
                materiDTO.setSubStatus(materialsmxDTO.getSubStatus());
                String deptName = sysDeptService.getDeptName(materiDTO.getCanteenId()).getName()+"主食采购清单";
                materiDTO.setChedRemake(deptName);
                auxiliaryDTO.add(materiDTO);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",auxiliaryDTO);
        int pending =0;//计算未处理订单的数量
        for (AuxiliaryMateriDTO materiDTO: auxiliaryDTO )  {
            if(0 ==materiDTO.getSubStatus()){
                pending = pending+1;
            }
        }
        map.put("pending",pending);
        return map;
    }
    /**
     * 获取待处理的数量
     * @param chedId
     * @param clerkId
     * @param canteenId
     * @param status
     * @return
     */
    @Override
    public AuxiliaryMateriDTO getTotal(Long chedId, Long clerkId, Long canteenId, int status) {
        String ched_Id="";
        String clerk_Id="";
        String canteen_Id="";
        if(null != chedId){
            ched_Id = " and  ched_id = "+chedId;
        }
        if(null != clerkId){
            clerk_Id = " and  canteen_admin_id = "+clerkId;
        }
        if(null != canteenId){
            canteen_Id = " and  canteen_id = "+canteenId;
        }
        AuxiliaryMateriDTO total = auxiliaryMateriDao.getTotal(ched_Id, clerk_Id, canteen_Id, status);
        return total;
    }
}